package cc.wfu.domain.order.service;

import cc.common.types.entity.ProductActivityEntity;
import cc.wfu.domain.order.model.entity.PayOrderEntity;
import cc.wfu.domain.order.model.entity.ProductActivitySkuEntity;
import cc.wfu.domain.order.model.valobj.PayStatusVO;
import cc.wfu.domain.order.repository.IProductActivityRepository;
import cc.wfu.domain.order.service.rule.factory.DefaultActivityChainFactory;
import cc.wfu.types.snow.SnowflakeIdGenerator;
import cc.wfu.types.weixin.PaySignUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 商品活动支撑类
 * @Date: 2024-06-05-21:53
 */
@Slf4j
@Component
public class ProductActivitySupport {

    @Value("${wxpay.config.appid}")
    private String appid;
    @Value("${wxpay.config.mchid}")
    private String mchid;
    @Value("${wxpay.config.notify-url}")
    private String notifyUrl;

    @Value("${personal.wxpay.mchId}")
    private String personalMchId;
    @Value("${personal.wxpay.key}")
    private String personalKey;
    @Value("${personal.wxpay.notifyUrl}")
    private String personalNotifyUrl;
    @Value("${personal.wxpay.url}")
    private String personalUrl;

    @Resource
    protected  IProductActivityRepository activityRepository;
    @Resource
    protected  DefaultActivityChainFactory defaultActivityChainFactory;
    @Resource
    protected SnowflakeIdGenerator snowflakeIdGenerator;

    /**
     * 通过sku查询活动商品信息
     * @param sku sku
     */
    public ProductActivitySkuEntity queryActivitySku(Long sku) {
        return activityRepository.queryActivitySku(sku);
    }

    /**
     * 查询活动商品信息
     * @param productId 商品ID
     */
    public ProductActivityEntity queryProductActivityByActivityId(Long productId) {
        return activityRepository.queryProductActivityByProductId(productId);
    }


    /**
     * 创建支付单 - 生成支付二维码 url
     * @param userId 用户ID
     * @param orderId 订单ID
     * @param productName 商品名
     * @param amountTotal 实际支付金额
     * @return 支付二维码 url
     */
    protected PayOrderEntity doPersonalPrepayOrder(String userId, String orderId, String productName, String amountTotal) {
        //当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", personalMchId);
        map.put("out_trade_no", orderId);
        map.put("total_fee", amountTotal);
        map.put("body", productName);
        map.put("notify_url", personalNotifyUrl);
        map.put("timestamp", timestamp);
        String sign = PaySignUtil.createSign(map, personalKey);
        map.put("sign", sign);
        String result = HttpRequest.post(personalUrl)
                .form(map)
                .execute()
                .body();
        String msg = "";
        if (StrUtil.isBlank(result)) {
            msg = "API接口返回为空，请联系客服";
        } else {
            try {
                JSONObject jsonObject = (JSONObject)JSONObject.parse(result);
                Integer code = jsonObject.getInteger("code");
                if(code == 0){
                    String qrcode = jsonObject.getJSONObject("data").getString("QRcode_url");
                    msg = "请使用微信扫码下方二维码:" + qrcode;
                    // 构造支付实体
                    PayOrderEntity payOrderEntity = PayOrderEntity.builder()
                            .userId(userId)
                            .orderId(orderId)
                            .payUrl(qrcode)
                            .payStatus(PayStatusVO.WAIT) // 等待支付
                            .build();
                    // 更新订单支付信息
                    activityRepository.updateOrderPayInfo(payOrderEntity);
                    return payOrderEntity;
                } else {
                    String msgStr = jsonObject.getString("msg");
                    msg = "返回失败：" + msgStr;
                }
            } catch (Exception e) {
                log.error("生成支付单出错: ", e);
            }
        }
        log.info(msg);
        return null;
    }


}
